<?php

namespace app\adminapi\controller;

use app\adminapi\model\Content;
use think\Controller;
use think\Db;
use think\Request;

class News extends Common
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $list = \app\adminapi\model\News::field('id,title,writer,create_time,update_time')->order('id desc')->paginate(10);
        $this->ok($list);
    }


    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //接收数据
        $params = input();
        $params['writer'] = $params['username'];
        //验证参数
        $validate = $this->validate($params, [
            'title|标题' => 'require|chs',
            'content|内容' => 'require',
        ]);
        if ($validate !== true) {
            $this->fail($validate);
        }
        //开启事务
        Db::startTrans();

        try {
            //添加数据
            $news = \app\adminapi\model\News::create($params, true);
            $params['n_id'] = $news['id'];
            //保存到详情表
            Content::create($params, true);
            $res = \app\adminapi\model\News::with('content')->find($news['id']);
            $data = [
                'id' => $res['id'],
                'title' => $res['title'],
                'writer' => $res['writer'],
                'content' => $res['content']['content'],
                'create_time' => $res['create_time'],
                'update_time' => $res['create_time'],
            ];
            //提交事务
            Db::commit();
            //返回数据
            $this->ok($data);

        } catch (\Exception $e) {
            //回滚事务
            Db::rollback();
            $this->fail('添加失败');
        }
    }

    /**
     * 显示指定的资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function read($id)
    {
        $res = \app\adminapi\model\News::with('content')->field('id,title,writer,create_time,update_time')->find($id);
        $data = [
            'id' => $res['id'],
            'title' => $res['title'],
            'writer' => $res['writer'],
            'content' => $res['content']['content'],
            'create_time' => $res['create_time'],
            'update_time' => $res['create_time'],
        ];
        $this->ok($data);
    }

}
